寫應用程式最重要的一塊就是跟資料庫串接,本日今日將討論Web開發常見的組合之一SSM(Spring MVC、Spring、Mybatis),來創建一個簡單的存取DB的簡單範例
在mapper interface name可以快速產生對應xml
在method可以在xml產生對應sql select
schema.sql
CREATE TABLE employees (
emp_no INT NOT NULL,
emp_name VARCHAR(14) NOT NULL
);
data.sql
INSERT INTO employees (emp_no,emp_name)
VALUES
('1','james syu'),
('2','Josph Lin');
Bean
@Data
public class Employee {
private int empId;
private String empName;
}
Mapper
public interface EmpMapper {
Employee getEmpById(@Param("id") int id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.swj.mapper.EmpMapper">
<select id="getEmpById" resultType="com.swj.bean.Employee">
select * from EMPLOYEES
where emp_no = #{id}
</select>
</mapper>
spring:
datasource:
driver-class-name: 'org.h2.Driver'
url: 'jdbc:h2:mem:springdb'
username: 'sa'
password:
h2:
console:
enabled: true #啟動web console操作頁面
sql:
init: #設定系統啟動初始化SQL
schema-locations: 'classpath:sql/schema.sql'
data-locations: 'classpath:sql/data.sql'
mybatis:
mapper-locations: 'classpath:/mapper/*.xml' #mapper對應的xml設定檔位置
configuration:
map-underscore-to-camel-case: true #啟動sql colnun name aaa_bbb 轉成 aaaBbb
@Slf4j
@RestController
public class EmpController {
@Autowired
EmpMapper empMapper;
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable int id){
log.info("EmpController get:"+id);
Employee emp = empMapper.getEmpById(id);
return emp;
}
}